package com.panda.web.utils.payutils;

import org.apache.commons.codec.digest.DigestUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

public class MiniWxPayUtil {

    // 生成随机字符串
    public static String generateNonceStr() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    // 生成签名
    public static String generateSignature(Map<String, String> data, String key) throws Exception {
        Set<String> keySet = data.keySet();
        String[] keyArray = keySet.toArray(new String[keySet.size()]);
        Arrays.sort(keyArray);

        StringBuilder sb = new StringBuilder();
        for (String k : keyArray) {
            if (data.get(k) != null && data.get(k).trim().length() > 0) {
                sb.append(k).append("=").append(data.get(k).trim()).append("&");
            }
        }
        sb.append("key=").append(key);
        return DigestUtils.md5Hex(sb.toString()).toUpperCase();
    }

    // Map转XML
    public static String mapToXml(Map<String, String> data) {
        StringBuilder xml = new StringBuilder("<xml>");
        for (Map.Entry<String, String> entry : data.entrySet()) {
            xml.append("<").append(entry.getKey()).append(">")
               .append(entry.getValue())
               .append("</").append(entry.getKey()).append(">");
        }
        xml.append("</xml>");
        return xml.toString();
    }

    // XML转Map
    public static Map<String, String> xmlToMap(String xml) throws Exception {
        Map<String, String> map = new HashMap<>();
        Document document = DocumentHelper.parseText(xml);
        Element root = document.getRootElement();
        for (Iterator<Element> it = root.elementIterator(); it.hasNext();) {
            Element element = it.next();
            map.put(element.getName(), element.getText());
        }
        return map;
    }
//    private Map<String, String> xmlToMap(HttpServletRequest request) throws Exception {
//        try (InputStream inputStream = request.getInputStream()) {
//            if (inputStream == null) {
//                throw new IOException("输入流为空");
//            }
//
//            // 使用dom4j解析XML
//            SAXReader reader = new SAXReader();
//            Document document = reader.read(inputStream);
//
//            // 获取所有子节点
//            Map<String, String> map = new HashMap<>();
//            List<Element> elements = document.getRootElement().elements();
//            for (Element element : elements) {
//                map.put(element.getName(), element.getTextTrim());
//            }
//
//            return map;
//        } catch (Exception e) {
//            log.error("解析微信支付回调XML数据失败", e);
//            throw new Exception("解析XML失败", e);
//        }
//    }
}